﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class Initialize : System.Web.UI.Page
{
    private string ConnectionString = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        ServStatusLab.Text = "";
    }
    protected void ServConnectionBtn_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(ServIP.Text))
        {
            ServStatusLab.ForeColor = System.Drawing.Color.OrangeRed;
            ServStatusLab.Text = "数据库服务IP地址不能为空。";
            return;
        }
        if (string.IsNullOrWhiteSpace(ServPwd.Text))
        {
            ServStatusLab.ForeColor = System.Drawing.Color.OrangeRed;
            ServStatusLab.Text = "数据库服务连接用户名不能为空";
            return;
        }
        if (string.IsNullOrWhiteSpace(ServUsr.Text))
        {
            ServStatusLab.ForeColor = System.Drawing.Color.OrangeRed;
            ServStatusLab.Text = "数据库服务连接密码不能为空";
            return;
        }
        ConnectionString = string.Format("Data Source={0};Persist Security Info=True;User ID={1};Password={2};", ServIP.Text, ServUsr.Text, ServPwd.Text);
        SqlConnection Connection = new SqlConnection(ConnectionString);
        try
        {
            Connection.OpenDb();
            ServStatusLab.ForeColor = System.Drawing.Color.Green;
            ServStatusLab.Text = "数据库服务连接成功，请继续其他操作。";
        }
        catch
        {
            ServStatusLab.ForeColor = System.Drawing.Color.OrangeRed;
            ServStatusLab.Text = "数据库服务连接失败，请检查填写的信息。";
        }
        finally
        {
            Connection.CloseDb();
        }
    }
    protected void ServActiveBtn_Click(object sender, EventArgs e)
    {
        ServStatusLab.Text = "";
        ConnectionString = string.Format("Data Source={0};Persist Security Info=True;User ID={1};Password={2};", ServIP.Text, ServUsr.Text, ServPwd.Text);
        SqlConnection Connection = new SqlConnection(ConnectionString);
        try
        {
            Connection.OpenDb();
            //string upfile = Request.Form["SQLFileUpl"];
            if (SQLFileUpl.HasFile)
            {
                string filename = System.Web.HttpContext.Current.Server.MapPath("~/") + SQLFileUpl.FileName;

                SQLFileUpl.SaveAs(filename);
                string args = String.Format(" -U {0} -P {1} -S {2} -i {3}", ServUsr.Text, ServPwd.Text, ServIP.Text, filename);
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = "osql.exe";
                psi.Arguments = args;
                psi.WindowStyle = ProcessWindowStyle.Hidden;
                psi.UseShellExecute = false;
                psi.RedirectStandardOutput = true;
                Process p = new Process();
                p.StartInfo = psi;
                p.Start();
                string p_result = p.StandardOutput.ReadToEnd();
                p.WaitForExit();
                //ServStatusLab.Text = p_result;
                File.Delete(filename);
                /*
                 * 如果是恢复数据库，那么此处连接数据库进行验证是否导入成功
                 * 如果是添加作业，不知道咋验证。
                 * 如果是建表，用sql语句验证是否成功
                 */

            }
            else
            {
                ServStatusLab.ForeColor = System.Drawing.Color.OrangeRed;
                ServStatusLab.Text = "未选择任何文件，请先选择文件。";
            }
        }
        catch (Exception ex)
        {
            ServStatusLab.ForeColor = System.Drawing.Color.OrangeRed;
            ServStatusLab.Text = ex.Message;
            return;
        }
        finally
        {
            Connection.CloseDb();
        }
    }
    protected void WebConfigChanged_Click(object sender, EventArgs e)
    {
        XmlDocument cfgDoc = new XmlDocument();
        cfgDoc.Load(HttpContext.Current.Server.MapPath("~/web.config"));
        XmlNode node = cfgDoc.SelectSingleNode("//connectionStrings");
        if (node == null)
        {
            node = cfgDoc.SelectSingleNode("//configuration");
            XmlElement entry = cfgDoc.CreateElement("connectionStrings");
            entry.AppendChild(cfgDoc.CreateElement("clear"));
            node.AppendChild(entry);
            XmlTextWriter writer = new XmlTextWriter(HttpContext.Current.Server.MapPath("~/web.config"), null);
            writer.Formatting = Formatting.Indented;
            cfgDoc.WriteTo(writer);
            writer.Flush();
            writer.Close();
            node = cfgDoc.SelectSingleNode("//connectionStrings");
        }
        try
        {

            XmlElement addElem = (XmlElement)node.SelectSingleNode("//add[@name='" + ConnectionKey.Text + "']");
            if (addElem != null)
            {
                ServStatusLab.Text = "数据库连接字串已经存在。";
            }
            else
            {
                XmlElement entry = cfgDoc.CreateElement("add");
                entry.SetAttribute("name", ConnectionKey.Text);
                entry.SetAttribute("connectionString", ServSqlConnection.Text);
                entry.SetAttribute("providerName", "System.Data.SqlClient");
                node.AppendChild(entry);
                //save it   
                XmlTextWriter writer = new XmlTextWriter(HttpContext.Current.Server.MapPath("~/web.config"), null);
                writer.Formatting = Formatting.Indented;
                cfgDoc.WriteTo(writer);
                writer.Flush();
                writer.Close();
                ServStatusLab.Text = "数据库连接字串创建成功。";
            }
        }
        catch
        {
        }
    }
}
